package gstyle.stylesheet;

import com.google.gwt.core.client.GWT;
import gstyle.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class SimpleStyleSheet implements StyleSheet {
    protected List styles = new ArrayList();
    private static int styleCount = 0;

    public static String autoGenerateIdOrStyleName() {
        return "s" + styleCount++;
    }

    public <T extends Style> T with(T style) {
        styles.add(style);
        return style;
    }

    public void apply() {
        GeneralCompiler generalCompiler = new GeneralCompiler();
        final StringBuffer buffer = new StringBuffer();
        for (Iterator iterator = styles.iterator(); iterator.hasNext();) {
            Style style = (Style) iterator.next();
            buffer.append(generalCompiler.compile(style));
        }
        ((StyleElementInjector)GWT.create(StyleElementInjector.class)).injectStyle(buffer.toString());
    }

    public ElementTag forTag(String name) {
        return with(new ElementTag(name));
    }

    public ElementId id() {
        return id(autoGenerateIdOrStyleName());
    }

    public ElementId id(String id) {
        return with(new ElementId(id));
    }

    public CssClass cssClass() {
        return cssClass(autoGenerateIdOrStyleName());
    }

    public CssClass cssClass(String name) {
        return with(new CssClass(name));
    }
}
